<template>
    <nly-content-wrapper>
        <nly-content>
            <div style="margin-top: 100px;margin-left: 100px; float: left;">
                <a-upload list-type="picture-card" class="avatar-uploader" :show-upload-list="false" :action="this.$Global.ApiBaseUrl + '/uploadFile'" :before-upload="beforeUpload" :headers="header" @change="handleChange">
                    <a-avatar :size="110" icon="user" v-if="imageUrl" :src="imageUrl" />
                    <div v-else>
                        <a-icon :type="loading ? 'loading' : 'plus'" />
                        <div class="ant-upload-text">点击上传头像</div>
                    </div>
                </a-upload>
                <div style="margin-left: 30px;">{{realName}}</div>
                <div style="margin-top: 10px; margin-left: 15px;">
                    <a-radio-group name="gender" v-model="userInfo.sex" :default-value="1">
                        <a-radio :value="1">男</a-radio>
                        <a-radio :value="0">女</a-radio>
                    </a-radio-group>
                </div>
                <div style="margin-top: 15px; width: 150px; margin-left: -15px;">
                    <a-button type="primary" size="small" block @click="() => (passwordVisible = true)">修改密码</a-button>
                </div>
            </div>
            <div>
                <div style="width:500px;margin-left: 350px;margin-top: -230px;">
                    <a-form :form="form" :label-col="{span: 5}" :wrapper-col="{span: 18}" class="user-class">
                        <a-form-item label="登录账号">
                            <a-input-search v-model="userInfo.userName" read-only style="width: 350px" @search="() => {this.updatePhoneVisible = true}">
                                <a-button slot="enterButton" type="primary">更换</a-button>
                            </a-input-search>
                        </a-form-item>
                        <a-form-item label="用户姓名">
                            <a-input v-model="userInfo.realName" style="width: 350px">
                                <a-icon slot="prefix" type="user" />
                            </a-input>
                        </a-form-item>
                        <a-form-item label="手机号">
                            <a-input v-model="userInfo.mobile" :disabled="false" style="width: 350px">
                                <!-- <a-button slot="enterButton">更换</a-button> -->
                                <a-icon slot="prefix" type="phone" />
                            </a-input>
                        </a-form-item>
                        <a-form-item label="电子邮箱">
                            <a-input v-model="userInfo.email" style="width: 350px">
                                <a-icon slot="prefix" type="mail" />
                            </a-input>
                        </a-form-item>
                        <a-form-item label="用户类型">
                            <a-radio-group style="float:left;margin-top:8px;text-align:center;color:red;position:relative" name="gender" @change="changeRoleData" v-model="userType" :default-value="1">
                                <a-radio :value="1">个人</a-radio>
                                <a-radio :value="2">单位</a-radio>
                            </a-radio-group>
                            <div style="position:absolute;width:136px;height:34px;background:rgba(255,255,255,0.1);z-index:3">

                            </div>
                            <a-button style="float:left;margin-left:149px" type="primary" @click="changeRole">变更</a-button>
                        </a-form-item>
                        <a-form-item label="任职部门" v-if="userInfo.companyName != null">
                            <a-input v-model="userInfo.officeName" read-only style="width: 350px">
                                <a-icon slot="prefix" type="team" />
                            </a-input>
                        </a-form-item>
                        <a-form-item label="任职公司" v-if="userInfo.companyName != null">
                            <a-input-search v-model="userInfo.companyName" read-only style="width: 350px;" @search="dimissionHandler">
                                <a-button slot="enterButton" type="primary">离职</a-button>
                            </a-input-search>
                        </a-form-item>
                        <a-form-item label="个性签名">
                            <a-textarea placeholder="请输入个性签名" v-model="userInfo.sign" style="width: 350px" />
                        </a-form-item>
                        <!-- <a-form-item label="上次登录时间">{{userInfo.lastLoginDate}} <span v-if="userInfo.companyName == null" @click="() => {this.updateUserTypeVisible = true}" style="margin-left: 150px;color: #1890ff"><a>升级为单位</a></span></a-form-item> -->
                        <a-form-item :wrapper-col="{ span: 12, offset: 9 }">
                            <a-button type="primary" html-type="submit" @click="saveUserInfo">保存</a-button>
                            <a-button html-type="submit" style="margin-left: 15px;" @click="closeInfo">关闭</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </div>
            <a-modal v-model="passwordVisible" title="修改密码" centered on-ok="handleok" width="650px">
                <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout">
                    <a-form-model-item has-feedback label="旧密码" prop="oldPwd">
                        <a-input v-model="ruleForm.oldPwd" type="password" />
                    </a-form-model-item>
                    <a-form-model-item has-feedback label="新密码" prop="pwd">
                        <a-input v-model="ruleForm.pwd" type="password" autocomplete="off" />
                    </a-form-model-item>
                    <a-form-model-item has-feedback label="确认新密码" prop="checkPwd">
                        <a-input v-model="ruleForm.checkPwd" type="password" autocomplete="off" />
                    </a-form-model-item>
                </a-form-model>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="saveUserPassword('ruleForm')">保存</a-button>
                    <a-button key="back" @click="() => (passwordVisible = false)">取消</a-button>
                </template>
            </a-modal>
            <a-modal v-model="updatePhoneVisible" title="修改登录账号" centered>
                <a-input v-model="loginPhone" placeholder="请输入登录手机号" style="width: 350px" />
                <a-input-search style="width: 350px; margin-top: 15px;" placeholder="请输入手机验证码" @search="sendSms" v-model="vCode">
                    <a-button slot="enterButton" type="primary" :disabled="isSendSms">{{codeCotent}}</a-button>
                </a-input-search>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="updateLoginPhone">立即更换</a-button>
                    <a-button key="back" @click="() => (updatePhoneVisible = false)">取消</a-button>
                </template>
            </a-modal>
            <a-modal v-model="updateUserTypeVisible" title="变更为单位用户" centered>
                <a-input v-model="companyName" placeholder="请输入单位名称" style="width: 350px" />
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="updateUserType">立即变更</a-button>
                    <a-button key="back" @click="() => (updateUserTypeVisible = false)">取消</a-button>
                </template>
            </a-modal>
        </nly-content>
        <!--加载中-->
        <div class="loading-wrapper" style="top:-1px" v-show="loadingRole">
            <a-spin class="loading-content" tip="用户类型变更中..." />
        </div>
    </nly-content-wrapper>
</template>

<script>
import Vue from "vue";
import { save, getUserInfo, checkPwd, savePwd, updateLoginPhone, updateUserType, updateCompanyType } from "@/api/personal/userInfo";
import { sendUserCode } from "@/api/user";
import { byebye } from "@/api/personal/userInfo";
import { mapState } from "vuex";
export default {
    data () {
        let checkPending;
        let numReg = /^[0-9]*$/;

        let checkOldPwd = (rule, value, callback) => {
            clearTimeout(checkPending);
            if (!value) {
                return callback(new Error("请输入旧密码"));
            }
            checkPending = setTimeout(() => {
                checkPwd({ pwd: value }).then(response => {
                    if (response.code == 200) {
                        callback();
                    } else {
                        callback(new Error("密码不正确！"));
                    }
                });
            }, 100);
        };
        let validatePwd = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请输入新密码"));
            } else {
                if (value.length < 6 || value.length > 14) {
                    callback(new Error("密码长度为6~14个字符"));
                }
                if (new RegExp(numReg).test(value)) {
                    callback(new Error("密码不能是纯数字"));
                }
                if (this.ruleForm.checkPass !== "") {
                    this.$refs.ruleForm.validateField("checkPass");
                }
                callback();
            }
        };
        let validatePwd2 = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请输入确认新密码"));
            } else if (value != this.ruleForm.pwd) {
                callback(new Error("两次输入的密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            ruleForm: {
                oldPwd: "",
                pwd: "",
                checkPwd: ""
            },
            rules: {
                oldPwd: [{ validator: checkOldPwd, trigger: "change" }],
                pwd: [{ validator: validatePwd, trigger: "change" }],
                checkPwd: [{ validator: validatePwd2, trigger: "change" }]
            },
            layout: {
                labelCol: { span: 4 },
                wrapperCol: { span: 14 }
            },
            loading: false,
            loadingRole: false,
            imageUrl: "",
            companyName: "",
            header: { "Access-Token": Vue.ls.get("Access-Token") },
            userInfo: {},
            formLayout: "horizontal",
            form: this.$form.createForm(this, { name: "coordinated" }),
            lastLoginDate: "2020-07-14 16:55:59",
            passwordVisible: false,
            updatePhoneVisible: false,
            updateUserTypeVisible: false,
            isSendSms: false,
            loginPhone: "",
            codeCotent: "发送验证码",
            vCode: "",
            realName: '',

            userType: null,
        };
    },
    mounted () {
        this.getUserInfo();
    },
    methods: {
        handleChange (info) {
            console.log(info);
            if (info.file.status === "uploading") {
                this.loading = true;
                return;
            }
            if (info.file.status === "done") {
                this.imageUrl = info.file.response.url;
                this.loading = false;
            }
        },
        beforeUpload (file) {
            const isJpgOrPng =
                file.type === "image/jpeg" || file.type === "image/png";
            if (!isJpgOrPng) {
                this.$message.error("只能选择图片!");
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error("图片不能超过2MB!");
            }
            return isJpgOrPng && isLt2M;
        },
        //获取用户详情
        getUserInfo () {
            getUserInfo().then(response => {
                if (response.code == 200) {
                    this.userInfo = { ...response.data };

                    if (this.userInfo.companyName) {
                        this.userType = 2;
                    } else {
                        this.userType = 1;
                    }
                    if (this.userInfo.avatar != null && this.userInfo.avatar != "") {
                        this.imageUrl = this.userInfo.avatar;
                        this.loading = false;
                        this.realName = this.userInfo.realName;
                    }
                }
            });
        },
        //保存用户信息
        saveUserInfo () {
            let emailTest = /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
            const sysUser = {};
            let email = this.userInfo.email;
            sysUser.avatar = this.imageUrl;
            sysUser.sex = this.userInfo.sex;
            sysUser.email = email;
            sysUser.sign = this.userInfo.sign;
            sysUser.id = this.userInfo.userId;
            sysUser.mobile = this.userInfo.mobile;
            sysUser.realName = this.userInfo.realName;
            if (sysUser.realName == null || (sysUser.realName.trim()).length < 1) {
                this.$message.error("用户姓名不能为空");
                return;
            }
            if (email == null || (email.trim()).length < 1) {
                this.$message.error("邮箱不能为空");
                return;
            } else if (!emailTest.test(email)) {
                this.$message.error("邮箱格式不正确");
                return;
            }
            save(sysUser).then(response => {
                if (response.code == 200) {
                    this.$store.commit('SET_AVATAR', this.imageUrl)
                    this.$message.success("保存成功");
                    this.getUserInfo();
                } else {
                    this.$message.error(response.message);
                }
            });
        },
        //修改用户密码
        saveUserPassword (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    savePwd(this.ruleForm).then(response => {
                        if (response.code == 200) {
                            this.$message.success("保存成功,请重新登录");
                            setTimeout(() => {
                                this.$store.dispatch("Logout").then(() => {
                                    this.$router.push({ path: "login" });
                                });
                            }, 1000);
                        } else {
                            this.$message.error(response.message);
                        }
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        //修改登录账号
        updateLoginPhone () {
            updateLoginPhone({ loginPhone: this.loginPhone, vCode: this.vCode }).then(
                response => {
                    if (response.code == 200) {
                        this.$message.success("保存成功,请重新登录");
                        setTimeout(() => {
                            this.$store.dispatch("Logout").then(() => {
                                this.$router.push({ path: "login" });
                            });
                        }, 1000);
                    } else {
                        this.$message.error(response.message);
                    }
                }
            );
        },
        changeRoleData (e) {
            console.log(e)
            this.userType = e.target.value;
        },
        changeRole () {
            if (this.userInfo.companyName != null) {
                //个人
                let _this = this;
                this.$confirm({
                    title: '确认',
                    content: <span style='color:red'>是否变更为个人用户？变更后，数据将不能恢复！</span>,
                    onOk () {
                        _this.loadingRole = true;
                        updateCompanyType().then(res => {
                            if (res.code === 200) {
                                _this.loadingRole = false;
                                _this.$message.success('变更成功请重新登录');
                                //刷新 列表
                                setTimeout(() => {
                                    _this.$store.dispatch("Logout").then(() => {
                                        _this.$router.push({ path: '/user/login' });
                                    });
                                }, 800)
                            } else {
                                _this.loadingRole = false;
                            }
                        })
                    },
                    onCancel () { },
                });
            } else {
                //企业
                this.updateUserTypeVisible = true;
            }
        },
        //变更为公司用户
        updateUserType () {
            this.updateUserTypeVisible = false;
            this.loadingRole = true;
            updateUserType({ companyName: this.companyName }).then(response => {
                if (response.code == 200) {
                    this.loadingRole = false;
                    this.$message.success("变更成功,请重新登录");
                    setTimeout(() => {
                        this.$store.dispatch("Logout").then(() => {
                            this.$router.push({ path: '/user/login' });
                        });
                    }, 1000);
                } else {
                    this.loadingRole = false;
                }
            });
        },
        //发送短信验证码
        sendSms () {
            if (this.loginPhone == null || this.loginPhone.length != 11) {
                this.$message.error("请输入正确的手机号");
                return;
            }

            sendUserCode({
                userPhone: this.loginPhone
            }).then(response => {
                if (response.code == 200) {
                    this.$message.success("发送成功");
                    let t = 60;
                    this.isSendSms = true;
                    let code = setInterval(() => {
                        if (t == 0) {
                            this.codeCotent = "发送验证码";
                            this.isSendSms = false;
                            clearInterval(code);
                            return false;
                        }
                        this.codeCotent = "获取验证码(" + t-- + ")";
                    }, 1000);
                } else {
                    this.$message.error(response.message);
                }
            });
        },
        //关闭
        closeInfo () {
            //console.log(this.$route);
            this.$store.commit("DELETE_TAB", this.$route.meta.key);
            this.$router.push({ path: "/dashboard/workplace" });
        },
        //离职
        dimissionHandler () {
            let _this = this;
            this.$confirm({
                title: '确认',
                content: "是否确认离职？",
                onOk () {
                    byebye({ id: _this.userInfo.id }).then(res => {
                        if (res.code === 200) {
                            _this.$message.success('离职成功');
                            //刷新 列表
                            setTimeout(() => {
                                _this.$store.dispatch("Logout").then(() => {
                                    _this.$router.push({ path: "login" });
                                });
                            }, 800)
                        }
                    })
                },
                onCancel () { },
            });
        },
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
</style>
<style>
    .avatar-uploader > .ant-upload {
        width: 110px;
        height: 110px;
    }
    .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
    }
    .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
    }
    .user-class .ant-form-item {
        margin-bottom: 2px !important;
    }
</style>